using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class EntityManager : MonoBehaviour
{
    Dictionary<string,GameObject> m_Entities = new Dictionary<string,GameObject>();
    public Dictionary<string,Transform> m_EntityGroups = new Dictionary<string,Transform>();

    private Transform m_EntityParent;

    public void Awake()
    {
        m_EntityParent = this.transform.parent.Find("Entity");
    }

    public void SetEntityGroup(List<string> groups)
    {
        for (int i = 0; i < groups.Count; i++)
        {
            GameObject go = new GameObject("Group-" + groups[i]);
            go.transform.SetParent(m_EntityParent, false);
            this.m_EntityGroups.Add(groups[i], go.transform);
        }
    }

    private Transform GetEntityGroup(string group)
    {
        if (!m_EntityGroups.ContainsKey(group))
            Debug.LogErrorFormat("group {0} not exsit", group);
        return m_EntityGroups[group];
    }

    public void ShowEntity(string entityName, string group, string luaName)
    {
        GameObject entity = null;
        if (m_Entities.TryGetValue(entityName, out entity))
        {
            EntityLogic entityLogic = entity.GetComponent<EntityLogic>();
            entityLogic.OnShow();
            return;
        }
        else
        {
            Manager.Resource.LoadPrefab(entityName, (UnityEngine.Object obj) =>
            {
                entity = Instantiate(obj) as GameObject;
                m_Entities.Add(entityName, entity);

                Transform parent = GetEntityGroup(group);
                entity.transform.SetParent(parent, false);
                
                EntityLogic entityLogic = entity.AddComponent<EntityLogic>();
                entityLogic.Init(luaName);
                entityLogic.OnShow();
            });
        }
    }
}
